<template>
  <div class="space-y-6">
    <!-- 页面标题和操作 -->
    <div class="flex justify-between items-center">
      <h2 class="text-2xl font-bold text-gray-900">新闻管理</h2>
      <el-button type="primary" @click="showAddDialog">
        <i class="fas fa-plus mr-2"></i>
        添加新闻
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="bg-white rounded-lg shadow-sm p-6 border border-gray-200">
      <div class="grid grid-cols-1 md:grid-cols-5 gap-4">
        <el-input
          v-model="searchForm.title"
          placeholder="新闻标题"
          clearable
        >
          <template #prefix>
            <i class="fas fa-newspaper text-gray-400"></i>
          </template>
        </el-input>
        <el-input
          v-model="searchForm.author"
          placeholder="作者"
          clearable
        >
          <template #prefix>
            <i class="fas fa-user-edit text-gray-400"></i>
          </template>
        </el-input>
        <el-select v-model="searchForm.status" placeholder="状态" clearable>
          <el-option label="全部状态" value=""></el-option>
          <el-option label="上线" value="1"></el-option>
          <el-option label="下线" value="0"></el-option>
        </el-select>
        <el-select v-model="searchForm.isRecommended" placeholder="推荐状态" clearable>
          <el-option label="全部" value=""></el-option>
          <el-option label="推荐" value="1"></el-option>
          <el-option label="普通" value="0"></el-option>
        </el-select>
        <div class="flex space-x-2">
          <el-button type="primary" @click="handleSearch">
            <i class="fas fa-search mr-2"></i>
            搜索
          </el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>
      </div>
    </div>

    <!-- 新闻列表 -->
    <div class="bg-white rounded-lg shadow-sm border border-gray-200">
      <el-table
        :data="newsList"
        v-loading="loading"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="封面" width="100">
          <template #default="{ row }">
            <img
              :src="getImageUrl(row.cover)"
              :alt="row.title"
              class="news-cover-thumbnail"
              @error="handleImageError"
            >
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="200" />
        <el-table-column prop="author" label="作者" width="120" />
        <el-table-column prop="viewCount" label="浏览量" width="100" />
        <el-table-column label="分类" width="120">
          <template #default="{ row }">
            <div v-if="row.categoryIds && row.categoryIds.length > 0">
              <el-tag
                v-for="categoryId in row.categoryIds"
                :key="categoryId"
                size="small"
                class="mr-1"
              >
                {{ getCategoryName(categoryId) }}
              </el-tag>
            </div>
            <span v-else class="text-gray-400">未分类</span>
          </template>
        </el-table-column>
        <el-table-column label="推荐" width="80">
          <template #default="{ row }">
            <el-tag :type="row.isRecommended === 1 ? 'success' : 'info'">
              {{ row.isRecommended === 1 ? '推荐' : '普通' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '上线' : '下线' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="publishTime" label="发布时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.publishTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="340" fixed="right" align="center" >
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="showEditDialog(row)">
              <i class="fas fa-edit mr-1"></i>
              编辑
            </el-button>
            <el-button
              size="small"
              :type="row.status === 1 ? 'warning' : 'success'"
              @click="toggleNewsStatus(row)"  
            >
              <i class="fas fa-toggle-on mr-1"></i>
              {{ row.status === 1 ? '下线' : '上线' }}
            </el-button>
            <el-button
              size="small"
              :type="row.isRecommended === 1 ? 'info' : 'success'"
              @click="toggleRecommended(row)"
            >
              <i class="fas fa-star mr-1"></i>
              {{ row.isRecommended === 1 ? '取消推荐' : '推荐' }}
            </el-button>
            <el-button size="small" type="danger" @click="deleteNews(row)">
              <i class="fas fa-trash mr-1"></i>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="flex justify-center py-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 添加/编辑新闻对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="900px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="newsForm"
        :rules="formRules"
        label-width="100px"
      >
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
          <el-form-item label="新闻标题" prop="title" class="col-span-2">
            <el-input v-model="newsForm.title" />
          </el-form-item>
          <el-form-item label="作者" prop="author">
            <el-input v-model="newsForm.author" />
          </el-form-item>
          <el-form-item label="发布时间" prop="publishTime">
            <el-date-picker
              v-model="newsForm.publishTime"
              type="datetime"
              placeholder="选择发布时间"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-switch
              v-model="newsForm.status"
              :active-value="1"
              :inactive-value="0"
              active-text="上线"
              inactive-text="下线"
            />
          </el-form-item>
          <el-form-item label="推荐" prop="isRecommended">
            <el-switch
              v-model="newsForm.isRecommended"
              :active-value="1"
              :inactive-value="0"
              active-text="推荐"
              inactive-text="普通"
            />
          </el-form-item>
        </div>
        <el-form-item label="新闻分类" prop="categoryId" class="col-span-2">
          <div class="flex items-center gap-2">
            <el-select
              v-model="newsForm.categoryId"
              placeholder="请选择新闻分类"
              style="width: 200px"
              clearable
            >
              <el-option
                v-for="category in newsCategories"
                :key="category.id"
                :label="category.name"
                :value="category.id"
              />
            </el-select>
            <el-button
              type="primary"
              size="small"
              @click="showAddCategoryDialog"
              style="margin-left: 8px"
            >
              <i class="fas fa-plus mr-1"></i>
              添加分类
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="封面图片" prop="cover">
          <div class="cover-upload-container">
            <el-upload
              ref="uploadRef"
              class="cover-uploader"
              :action="uploadAction"
              :show-file-list="false"
              :before-upload="beforeCoverUpload"
              :on-success="handleCoverSuccess"
              :on-error="handleCoverError"
              :headers="uploadHeaders"
              accept="image/*"
              drag
            >
              <div v-if="newsForm.cover" class="cover-preview">
                <img :src="getImageUrl(newsForm.cover)" alt="封面预览" class="cover-image">
                <div class="cover-overlay">
                  <i class="fas fa-edit"></i>
                  <span>点击更换</span>
                </div>
              </div>
              <div v-else class="upload-placeholder">
                <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-3"></i>
                <div class="text-gray-600">
                  <p class="mb-2">点击或拖拽图片到此处上传</p>
                  <p class="text-sm text-gray-500">支持 JPG、PNG、GIF 格式，文件大小不超过 2MB</p>
                </div>
              </div>
            </el-upload>
          </div>
        </el-form-item>
        <el-form-item label="摘要" prop="summary">
          <el-input
            v-model="newsForm.summary"
            type="textarea"
            :rows="3"
            placeholder="请输入新闻摘要"
          />
        </el-form-item>
        <el-form-item label="内容" prop="content">
          <el-input
            v-model="newsForm.content"
            type="textarea"
            :rows="8"
            placeholder="请输入新闻内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加新闻分类对话框 -->
    <el-dialog
      v-model="categoryDialogVisible"
      title="添加新闻分类"
      width="400px"
      @close="resetCategoryForm"
    >
      <el-form
        ref="categoryFormRef"
        :model="categoryForm"
        :rules="categoryFormRules"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input
            v-model="categoryForm.name"
            placeholder="请输入分类名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="categoryDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCategoryForm" :loading="categorySubmitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { adminAPI } from '@/api/admin.js'

const loading = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()

const searchForm = reactive({
  title: '',
  author: '',
  status: '',
  isRecommended: ''
})

const newsForm = reactive({
  id: null,
  title: '',
  author: '',
  cover: '',
  summary: '',
  content: '',
  status: 1,
  isRecommended: 0,
  publishTime: new Date(),
  categoryId: null // 新闻分类ID（单选）
})

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const newsList = ref([])
const uploadRef = ref()
const newsCategories = ref([]) // 新闻分类列表

// 添加分类相关
const categoryDialogVisible = ref(false)
const categoryFormRef = ref()
const categorySubmitting = ref(false)
const categoryForm = reactive({
  name: '',
  description: ''
})

// 分类表单验证规则
const categoryFormRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 1, max: 50, message: '分类名称长度在 1 到 50 个字符', trigger: 'blur' }
  ]
}

// 上传配置
const uploadAction = ref('/api/admin/upload')
const uploadHeaders = computed(() => {
  const token = localStorage.getItem('token')
  return token ? { 'Authorization': `Bearer ${token}` } : {}
})

const dialogTitle = computed(() => isEdit.value ? '编辑新闻' : '添加新闻')

const formRules = {
  title: [
    { required: true, message: '请输入新闻标题', trigger: 'blur' },
    { min: 5, max: 100, message: '标题长度在 5 到 100 个字符', trigger: 'blur' }
  ],
  author: [{ required: true, message: '请输入作者', trigger: 'blur' }],
  content: [{ required: true, message: '请输入新闻内容', trigger: 'blur' }],
  publishTime: [{ required: true, message: '请选择发布时间', trigger: 'change' }]
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

const loadNewsList = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.currentPage,
      size: pagination.pageSize,
      ...searchForm
    }

    const response = await adminAPI.getNewsList(params)
    newsList.value = response.data.records || []
    pagination.total = response.data.total || 0
  } catch (error) {
    console.error('加载新闻列表失败:', error)
    ElMessage.error('加载新闻列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.currentPage = 1
  loadNewsList()
}

const resetSearch = () => {
  Object.assign(searchForm, {
    title: '',
    author: '',
    status: '',
    isRecommended: ''
  })
  handleSearch()
}

// 加载新闻分类列表
const loadNewsCategories = async () => {
  try {
    const response = await adminAPI.getNewsCategories()
    newsCategories.value = response.data || []
  } catch (error) {
    console.error('加载新闻分类失败:', error)
    ElMessage.error('加载新闻分类失败')
  }
}

// 显示添加分类对话框
const showAddCategoryDialog = () => {
  categoryDialogVisible.value = true
}

// 重置分类表单
const resetCategoryForm = () => {
  Object.assign(categoryForm, {
    name: '',
    description: ''
  })
  categoryFormRef.value?.resetFields()
}

// 提交分类表单
const submitCategoryForm = async () => {
  try {
    await categoryFormRef.value.validate()
    categorySubmitting.value = true

    const response = await adminAPI.createNewsCategory(categoryForm)
    ElMessage.success('分类添加成功')

    // 重新加载分类列表
    await loadNewsCategories()

    // 自动选择新添加的分类
    if (response.data && response.data.id) {
      newsForm.categoryId = response.data.id
    }

    categoryDialogVisible.value = false
    resetCategoryForm()
  } catch (error) {
    console.error('添加分类失败:', error)
    ElMessage.error(error.message || '添加分类失败')
  } finally {
    categorySubmitting.value = false
  }
}

const showAddDialog = () => {
  isEdit.value = false
  dialogVisible.value = true
}

const showEditDialog = (row) => {
  isEdit.value = true
  Object.assign(newsForm, {
    ...row,
    publishTime: new Date(row.publishTime),
    categoryId: row.categoryIds && row.categoryIds.length > 0 ? row.categoryIds[0] : null
  })
  dialogVisible.value = true
}

const resetForm = () => {
  Object.assign(newsForm, {
    id: null,
    title: '',
    author: '',
    cover: '',
    summary: '',
    content: '',
    status: 1,
    isRecommended: 0,
    publishTime: new Date(),
    categoryId: null
  })
  formRef.value?.resetFields()
}

const submitForm = async () => {
  try {
    await formRef.value.validate()

    // 准备提交数据，将单个categoryId转换为categoryIds数组
    const submitData = {
      ...newsForm,
      categoryIds: newsForm.categoryId ? [newsForm.categoryId] : []
    }
    // 删除categoryId字段，避免后端接收到不需要的字段
    delete submitData.categoryId

    if (isEdit.value) {
      await adminAPI.updateNews(newsForm.id, submitData)
      ElMessage.success('新闻更新成功')
    } else {
      await adminAPI.createNews(submitData)
      ElMessage.success('新闻添加成功')
    }

    dialogVisible.value = false
    resetForm()
    loadNewsList()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error(error.message || '操作失败')
  }
}

const toggleNewsStatus = async (row) => {
  try {
    const action = row.status === 1 ? '下线' : '上线'
    await ElMessageBox.confirm(`确定要${action}新闻 "${row.title}" 吗？`, '确认操作')

    const newStatus = row.status === 1 ? 0 : 1
    await adminAPI.toggleNewsStatus(row.id, newStatus)
    row.status = newStatus
    ElMessage.success(`新闻${action}成功`)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error)
      ElMessage.error('操作失败')
    }
  }
}

const toggleRecommended = async (row) => {
  try {
    const action = row.isRecommended === 1 ? '取消推荐' : '推荐'
    await ElMessageBox.confirm(`确定要${action}新闻 "${row.title}" 吗？`, '确认操作')
    
    // 模拟API调用
    row.isRecommended = row.isRecommended === 1 ? 0 : 1
    ElMessage.success(`新闻${action}成功`)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

const deleteNews = async (row) => {
  try {
    await ElMessageBox.confirm(`确定要删除新闻 "${row.title}" 吗？`, '确认删除', {
      type: 'warning'
    })

    await adminAPI.deleteNews(row.id)
    ElMessage.success('新闻删除成功')
    loadNewsList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error(error.message || '删除失败')
    }
  }
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadNewsList()
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadNewsList()
}

// 封面上传相关方法
const beforeCoverUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt20M = file.size / 1024 / 1024 < 20

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt20M) {
    ElMessage.error('图片大小不能超过 20MB!')
    return false
  }
  return true
}

const handleCoverSuccess = (response) => {
  if (response.code === 200) {
    newsForm.cover = response.data.url
    ElMessage.success('封面上传成功')
  } else {
    ElMessage.error(response.message || '上传失败')
  }
}

const handleCoverError = (error) => {
  console.error('上传失败:', error)
  ElMessage.error('封面上传失败')
}

const getImageUrl = (url) => {
  if (!url) return ''

  // 如果是完整的URL，直接返回
  if (url.startsWith('http')) {
    return url
  }

  // 如果是上传的文件路径
  if (url.startsWith('/uploads/')) {
    return `http://localhost:8081/api${url}`
  }

  // 如果是静态资源路径
  if (url.startsWith('/assets/')) {
    return `http://localhost:8081/api${url}`
  }

  // 其他情况，添加API前缀
  return `/api${url}`
}

// 根据分类ID获取分类名称
const getCategoryName = (categoryId) => {
  const category = newsCategories.value.find(cat => cat.id === categoryId)
  return category ? category.name : '未知分类'
}

// 图片加载错误处理
const handleImageError = (event) => {
  console.error('图片加载失败:', event.target.src)
  // 设置默认图片
  event.target.src = ''
}

onMounted(() => {
  loadNewsList()
  loadNewsCategories()
})
</script>

<style scoped>
.cover-upload-container {
  width: 100%;
  display: flex;
  justify-content: center;
}

.cover-uploader {
  width: 100%;
}

.cover-uploader :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: all 0.3s;
  width: 180px;
  height: 240px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f9f9f9;
}

.cover-uploader :deep(.el-upload:hover) {
  border-color: #409eff;
}

.cover-preview {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  box-sizing: border-box;
}

.cover-image {
  max-width: 160px;
  max-height: 220px;
  object-fit: contain;
  border-radius: 4px;
}

.cover-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
}

.cover-preview:hover .cover-overlay {
  opacity: 1;
}

.upload-placeholder {
  text-align: center;
  padding: 20px;
}

.upload-placeholder i {
  font-size: 48px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.news-cover-thumbnail {
  width: 60px;
  height: 40px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #e5e7eb;
  background-color: #f9f9f9;
}
</style>
